var express = require('express');
var router = express.Router();
var myQuery = require('../utils/db');
const { API_URL, verifyToken, getToken } = require('../utils/config.js')

var uuid = require('uuid');
var md5 = require('md5');
var jwt = require('jsonwebtoken');





let suozi = '我是锁子'
router.use((req,res,next)=>{
  // console.log(req.body);
  req.body.password = md5(req.body.password+suozi) 
  req.body.repwd = md5(req.body.repwd+suozi) 

  next()
})
/* GET home page. */
router.get('/demo3', function (req, res, next) {
  res.send('这是我们的登录注册模块')
});

//这是我们的登录注册

router.post('/register', async function (req, res, next) {
  let data = {}
  let { username, password, repwd } = req.body
  if (!username || !password || !repwd) {

    data = {
      "msg": "请填写用户名密码",
      "status": 500
    }
    res.send(data)
    return
  }
  if (username.length < 5 || username.length > 15) {

    data = {
      "msg": "用户名最小5位最长15位",
      "status": 500
    }
    res.send(data)
    return

  }
  if (password !== repwd) {

    data = {
      "msg": "密码不一致",
      "status": 500
    }
    res.send(data)
    return
  }

  let sql1 = `SELECT * FROM e_member WHERE username = '${username}';`
  let res1 = await myQuery(sql1)
  console.log(res1);
  if (res1.result.length >0) {
    data = {
      "msg": "该用户名已注册",
      "status": 400
    }
    res.send(data)
    return
  }
  let mid = uuid.v4();
  let time = Date.now()
  let sql2 = `INSERT INTO e_member (username,password,birthdate,mid) values ('${username}','${password}', ${time} , '${mid}' ) ; `
  let res2 = await myQuery(sql2)
  if (res2.result.affectedRows == 0) {
    data = {
      "msg": "稍后再试",
      "status": 400
    }
    res.send(data)
    return
  }
  data = {
    "msg": "OK",
    "status": 200
  }
  res.send(data)
});
router.post('/login', async function (req, res, next) {
  let data = {}
  let { username, password} = req.body

  console.log(username,password);
  if (!username || !password ) {

    data = {
      "msg": "请填写用户名密码",
      "status": 500
    }
    res.send(data)
    return
  }

  let sql1 = `SELECT * FROM e_member WHERE username = '${username}';`
  let res1 = await myQuery(sql1)
  console.log(res1);
  if (res1.result.length <= 0) {
    data = {
      "msg": "该用户未注册",
      "status": 400
    }
    res.send(data)
    return
  }


  let sql2 = `SELECT * FROM e_member WHERE username = '${username}' and password = '${password}';`
  let res2 = await myQuery(sql2)
  // console.log(password);
  console.log(res2);
  if (res2.result.length == 0) {
    data = {
      "msg": "用户名密码不正确",
      "status": 400
    }
    res.send(data)
    return
  }
  let mid = res2.result[0].mid
  // console.log(mid);
  
  // var token = jwt.sign({ username ,mid }, suozi);
  var token = getToken({username ,mid});
  // console.log(token);
  data = {
    "msg": "OK",
    "status": 200,
    token,
    mid
  }
  res.send(data)
});

module.exports = router;
